package com.yangli.leecode.mashib.graph;

/**
 * @Description 图 所有节点和所有边
 * @Author liyang
 * @Date 2023/1/5 17:17
 */

import java.util.*;

public class Graph {
    public HashMap<Integer, Node> nodes;
    public HashSet<Edge> edges;

    public Graph(){
        nodes = new HashMap<>();
        edges = new HashSet<>();
    }


    // 从node出发，进行宽度优先遍历
    public static void bfs(Node start){
        if (start == null) {
            return;
        }
        Queue<Node> queue = new LinkedList<>();
        HashSet<Node> set = new HashSet<>();
        queue.add(start);
        set.add(start);
        while (!queue.isEmpty()) {
            Node cur = queue.poll();
            for (Node node : cur.nexts) {
                System.out.println(node.value);
                if (!set.contains(cur)) {
                    set.add(node);
                    queue.add(node);
                }
            }
        }
    }


    public static void dfs(Node start){
        if (start == null) {
            return;
        }
        Stack<Node> stack = new Stack<>();
        HashSet<Node> set = new HashSet<>();
        stack.add(start);
        set.add(start);
        System.out.println(start.value);
        while (!stack.isEmpty()) {
            Node cur = stack.pop();
            for (Node next : cur.nexts) {
                if (!set.contains(next)) {
                    stack.push(cur);
                    stack.push(next);
                    set.add(next);
                    System.out.println(next.value);
                    break;
                }
            }
        }
    }
}
